"use strict";

window.onload = function () {
    setTimeout(function () {
        $(document).on('click', 'img', function (e) {
            e.preventDefault();
        });
    }, 1000)
}

var WORD_URL = 'http://www.xdocin.com/xdoc?_func=to&amp;_format=html&amp;_cache=1&amp;_xdoc=';

//异步延迟加载样式
function asynLoadCss(url) {
    var link = document.createElement('link');
    link.href = url;
    link.rel = 'stylesheet';
    document.head.appendChild(link);
}

//异步延迟加载js
function asynLoadJs(url) {
    var script = document.createElement('script');
    script.src = url;
    script.type = 'text/javascript';
    document.body.appendChild(script);
}

function initInputPlugin(length) {
    var parentClass = '.input-box';
    var childrenClass = parentClass + ' input';
    var inputCount = length;
    $(childrenClass).on('focus', function (evt) {
        var _this = this;
        if (!this.value) {
            var inputId = 1;
            while (inputId >= 1 && inputId <= inputCount) {
                // var inputDom = $('input[data-id=' + inputId + ']')[0];
                var inputDom = document.querySelector('input[data-id="' + inputId + '"]');
                // var inputDom = document.querySelector('input[data-id="' + inputId + '"]')[0];
                if (!inputDom.value) {
                    if (_this !== inputDom)
                        inputDom.focus();
                    break;
                }
                inputId++;
            }
        }
    })
    $(childrenClass).on('input', function (evt) {
        if (this.value && this.value.length >= 1) {
            var inputId = this.getAttribute('data-id');
            if (inputId < inputCount) {
                // var inputDom = $('input[data-id=' + ++inputId + ']')[0];
                var inputDom = document.querySelector('input[data-id="' + ++inputId + '"]');
                // var inputDom = document.querySelector('input[data-id="' + ++inputId + '"]')[0];
                inputDom.focus();
            }
        }
    })
    $(childrenClass).on('keyup', function (evt) {
        var code;
        if (evt.key !== undefined) {
            code = evt.key;
        } else if (evt.keyCode !== undefined) {
            code = evt.keyCode;
        }
        if (code === 8 || code === 'Backspace') {
            var inputId = this.getAttribute('data-id');
            if (inputId > 1) {
                // var inputDom = $('input[data-id=' + --inputId + ']')[0];
                var inputDom = document.querySelector('input[data-id="' + --inputId + '"]');
                inputDom.focus();
            }
        }
    })

}

function historyBack() {
    window.history.back();
}

function gotoLogin() {
    window.location.href = 'pages/login.html';
}

function backTop() {
    $('body,html').animate({scrollTop: 0}, 500);
}

function getClientSize() {
    return {
        clientWidth: (document.compatMode === "CSS1Compat") ? document.documentElement.clientWidth : document.body.clientWidth,
        clientHeight: (document.compatMode === "CSS1Compat") ? document.documentElement.clientHeight : document.body.clientHeight
    }
}

function comQuest(type, url, data, success) {
    $.ajax({
        type: type,
        url: url,
        data: data,
        dataType: 'json',
        async: false,
        cache: false,
        success: function (result) {
            success(result);
        }
    });
}

//活动时间
//显示状态描述
function showTimeDesc(item) {
    if (item.deadline && item.endtime) {
        if (new Date().getTime() > item.endtime)
            return '已过期';
        else if (new Date().getTime() > item.deadline)
            return '已截止';
        else
            return '正在报名';
    }
    return '已过期';
}

//时间分组
/**
 *
 * @param arr 原数组
 * @param field 时间字段
 * @returns {{data: *, time: string}[]|Array}
 */
function groupByTime(arr, field) {
    if (!arr || arr.length === 0) return [];
    var timeArr = [];
    arr.forEach(function (item) {
        var timeStr = getYearMonthDay(item[field], '-');
        if (!timeArr.includes(timeStr))
            timeArr.push(timeStr);
    })
    var result = {};
    timeArr.forEach(function (item) {
        result[item] = [];
    })
    arr.forEach(function (item) {
        result[getYearMonthDay(item[field], '-')].push(item);
    })
    return Object.keys(result).map(function (key) {
        return {
            time: key,
            data: result[key]
        };
    })
}

function getYearMonthDay(time, symbol) {
    var date = new Date(time);
    return date.getFullYear() + symbol + (date.getMonth() + 1) + symbol + date.getDate();
}


function validaTime(t1, t2) {
    var d1 = new Date(t1);
    var d2 = new Date(t2);
    if (d1.getFullYear() === d2.getFullYear()
        && d1.getMonth() === d2.getMonth()
        && d1.getDate() === d2.getDate())
        return true;
    return false;
}

function isToday(time) {
    return validaTime(time, new Date().getTime());
}


//页面添加遮罩层插件开始
var maskClassName = 'custom-mask';

function ShowMask(options) {
    var _this = this;
    this.options = options || {};
    //先查询是否存在mask dom元素，存在就显示
    var existDom = document.querySelector('.' + maskClassName);
    this.show = function () {
        existDom = document.querySelector('.' + maskClassName);
        !existDom ? document.body.appendChild(maskNode) : existDom.style.display = 'block';
    };
    this.close = function () {
        _this.options.closeCallBack && _this.options.closeCallBack();
        var timeoutTimer = setTimeout(function () {
            document.querySelector('.' + maskClassName).style.display = 'none';
            clearTimeout(timeoutTimer);
        }, _this.options.closeDuration || 600);
    }
    //不存在mask dom元素就创建。
    if (!existDom) {
        var maskNode = document.createElement('div');
        maskNode.className = maskClassName;
        var clientSizeObj = getClientSize();
        maskNode.style.height = clientSizeObj.clientHeight + 'px';
        maskNode.style.width = clientSizeObj.clientWidth + 'px';
        maskNode.style.position = 'fixed';
        maskNode.style.top = '0';
        maskNode.style.left = '0';
        maskNode.style.zIndex = '1000';
        maskNode.style.backgroundColor = 'rgba(0,0,0,0.26)';
        this.options.closeFlag && maskNode.addEventListener('click', this.close);
    }
}

//页面添加遮罩层插件结束


//数组左移右移位数
function moveElement(arr, n) {
    if (Math.abs(n) > arr.length) n = n % arr.length;
    return arr.slice(-n).concat(arr.slice(0, -n))
}

//对象是否为空
function isEmptyObject(obj) {
    return JSON.stringify(obj) === '{}';
}

//保存json对象
function setSessionJSON(key, object) {
    sessionStorage.setItem(key, JSON.stringify(object));
}

//获取json对象
function getSessionJSON(key) {
    try {
        return sessionStorage.getItem(key) ? JSON.parse(sessionStorage.getItem(key)) : {}
    } catch (e) {
        return {}
    }
}

//获取json数组
function getSessionJSONArr(key) {
    try {
        return sessionStorage.getItem(key) ? JSON.parse(sessionStorage.getItem(key)) : []
    } catch (e) {
        return []
    }
}

//控制浏览器返回开始
//控制浏览器后退
var browserBackwordLimit = function (callback) {
    window.addEventListener("popstate", function () {
        // alert("我监听到了浏览器的返回按钮事件啦");//根据自己的需求实现自己的功能
        if (callback)
            callback();
        window.history.pushState('forward', null, '#');
        window.history.forward(1);
    }, false)
    window.history.pushState('forward', null, '#');
    window.history.forward(1);
}
//控制浏览器返回结束

//使用插件——浏览器前进
var browserArrayKey = 'browserArray';
var browserForward = function (forwardHref) {
    var browserArr = getSessionJSONArr(browserArrayKey);
    browserArr.push(window.location.href);
    setSessionJSON(browserArrayKey, browserArr);
    window.location.href = forwardHref;
}
//使用插件——浏览器后退
var browserBackward = function () {
    var browserArr = getSessionJSONArr(browserArrayKey);
    if (browserArr.length > 0) {
        var backwardHref = browserArr.pop();
        setSessionJSON(browserArrayKey, browserArr);
        window.location.href = backwardHref;
    }
}
//使用插件——清空浏览器前进后退数组
var clearBrowserArr = function () {
    setSessionJSON(browserArrayKey, []);
}

//封装picker 一列数据
function handlePickerData(arr, valueKey, textAlign) {
    arr = arr || [];
    return [{
        textAlign: textAlign || 'center',
        values:
            arr.map(function (item) {
                return item[valueKey]
            })
    }]
}

function handlePickerTime(values) {
    return new Date(values[0] + '-' + values[1] + '-' + values[2] + ' ' + values[3] + ':' + values[4]).getTime();
}

//赋值picker数据
function updatePickData(target, id, newData) {
    target = target || [];
    return target.map(function (item) {
        if (item.id === id) item.cols = newData;
        return item;
    })
}

//picker 封装
function showPicker(options) {
    options = options || {};
    options.cols = options.cols || [];
    $(options.el).picker({
        title: options.title || "请选择",
        cols: options.cols,
        // value: options.value || [],
        items: options.items || [],
        onChange: function (p, values, displayValues) {
            options.onChange && options.onChange(p, values, displayValues);
        },
        onClose: function (p, values, displayValues) {
            options.onClose && options.onClose(p, values, displayValues);
        },
    });
    //打开
    $(options.el).picker("open");
}

//datepicker 封装
function showDatePicker(options) {
    options = options || {};
    // $(options.el).picker("close");
    $(options.el).datetimePicker({
        title: options.title || "请选择",
        onChange: function (p, values, displayValues) {
            options.onChange && options.onChange(p, values, displayValues);
        },
        onClose: function (p, values, displayValues) {
            options.onClose && options.onClose(p, values, displayValues);
        },
    });
    //打开
    $(options.el).picker("open");
}


function isDelete(method, id) {
    layui.use(['layer'], function () {
        layer.confirm('确认删除吗？', {
            icon: 2,
            title: false,
            closeBtn: 0,
            btn: ['确认', '取消'] //按钮
        }, function () {
            method(id);
        }, function () {
        });
    })
}

function openRemind(str, icon, time, callback) {
    layui.use(['layer'], function () {
        var layer = layui.layer;
        if (icon != 2) {
            layer.msg(str, {icon: icon, shade: [0.5, '#393D49'], time: time,},
                function () {
                    if (callback)
                        callback();
                });
        } else {
            layer.msg(str, {icon: icon, shade: [0.5, '#393D49'], time: time, anim: 6},
                function () {
                    if (callback)
                        callback();
                });
        }
    })
}

function pagination(jump, count, limit, element, layout, groups, prev, next) {
    layui.use(['layer', 'laypage'], function () {
        var layer = layui.layer;
        var laypage = layui.laypage;
        laypage.render({
            elem: element ? element : 'page'
            , count: count //数据总数，从服务端得到
            , limit: limit ? limit : 10
            , layout: layout ? layout : ['count', 'prev', 'page', 'next', /*'limit', 'refresh', */ 'skip']
            , groups: groups ? groups : 5
            , prev: prev ? prev : '上一页'
            , next: next ? next : '上一页'
            , jump: function (obj, first) {
                if (jump)
                    jump(obj, first);
            }
        });
    })
}

function getScope(controllerName) {
    //通过controller来获取Angular应用
    var appElement = document.querySelector('[ng-controller=' + controllerName + ']');
    //获取$scope变量
    return angular.element(appElement).scope();
}

function tokenInvalid(message) {
    if (message === '登录失效！' || message === 'token失效')
        setTimeout(function () {
            if (location.href.indexOf('index.html') != -1) {
                window.location.href = './pages/login.html';
            } else {
                window.location.href = './login.html';
            }
            return false;
        }, 1500)
}

function getHttp($http, serviceUrl, requestData, success, error) {
    $http({
        url: serverIP + serviceUrl,
        headers:{token:getToken()},
        method: "get",
        params :requestData
    }).success(function (res) {
        if (success){
            success(res);
            //每个接口请求记得一定要调用
            reloadJs();
        }
    }).error(function (data, status, headers, config) {
    	// location.href="index.html";
        if (error)
            error(data);
    });
}

function postFormHttp($http, serviceUrl, requestData, success, error) {
    $http({
        url: serverIP + serviceUrl,
        method: "post",
        data: $.param(requestData),
        headers: {'Content-Type': 'application/x-www-form-urlencoded'}
    }).success(function (res) {
        if (success)
            success(res);
    }).error(function (data, status, headers, config) {
        if (error)
            error(data);
    });
}

function postHttp($http, serviceUrl, requestData, success, error) {
    $http({
        url: serverIP + serviceUrl,
        method: "post",
        headers:{token:getToken()},
        data: requestData,
    }).success(function (res) {
        // tokenInvalid(res.message);
        if (success){
            success(res);
            //每个接口请求记得一定要调用
            reloadJs();
        }
    }).error(function (data, status, headers, config) {
    	sessionStorage.clear();
		localStorage.clear();
    	location.href="index.html";
        if (error)
            error(data);
    });
}
function postHttp2($http, serviceUrl, requestData, success, error) {
    $http({
        url: serviceUrl,
        method: "post",
        headers:{token:getToken()},
        data: requestData,
    }).success(function (res) {
        // tokenInvalid(res.message);
        if (success){
            success(res);
            //每个接口请求记得一定要调用
            reloadJs();
        }
    }).error(function (data, status, headers, config) {
    	location.href="index.html";
        if (error)
            error(data);
    });
}
function postHttpByIp($http, serviceUrl, requestData, success, error) {
        $http({
            url: serviceUrl,
            method: "post",
            data: requestData,
        }).success(function (res) {
            // tokenInvalid(res.message);
            if (success)
                success(res);
        }).error(function (data, status, headers, config) {
            if (error)
                error(data);
        });
}

function postHttpAsync($http, serviceUrl, requestData, success, error) {
    $http({
        url: serverIP + serviceUrl,
        method: "post",
        data: requestData,
    }).success(function (res) {
        if (success)
            success(res);
    }).error(function (data, status, headers, config) {
        if (error)
            error(data);
    });
}

function fileHttp($http, serviceUrl, formData, success, error) {
    $http({
        url: serverIP + serviceUrl,
        method: "post",
        headers:{token:getToken(),'Content-Type': undefined},
        data: formData,
        // headers: {'Content-Type': undefined},
        transformRequest: angular.identity
    }).success(function (res) {
        layer.close(index);

        if (success)
            success(res);
    }).error(function (data, status, headers, config) {
        if (error)
            error(data);
    });
}


function getUrlValue(field) {
    if (!location.search) return null;
    var params = location.search.split("?")[1].split("&");
    for (var i in params) {
        var map = params[i].split("=");
        if (field == map[0]) {
            return map[1];
        }
    }
    return null;
}

function getSearchUrlValue() {
    return window.location.search.substring(1);
}

Date.prototype.format = function (format) {
    var date = {
        "M+": this.getMonth() + 1,
        "d+": this.getDate(),
        "h+": this.getHours(),
        "m+": this.getMinutes(),
        "s+": this.getSeconds(),
        "q+": Math.floor((this.getMonth() + 3) / 3),
        "S+": this.getMilliseconds()
    };
    if (/(y+)/i.test(format)) {
        format = format.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length));
    }
    for (var k in date) {
        if (new RegExp("(" + k + ")").test(format)) {
            format = format.replace(RegExp.$1, RegExp.$1.length == 1 ?
                date[k] : ("00" + date[k]).substr(("" + date[k]).length));
        }
    }
    return format;
}
// console.log(new Date().format('yyyy-MM-dd h:m:s'));


var numToStringArr = [
    {id: 1, value: '一'},
    {id: 2, value: '二'},
    {id: 3, value: '三'},
    {id: 4, value: '四'},
    {id: 5, value: '五'},
    {id: 6, value: '六'},
    {id: 7, value: '七'},
    {id: 8, value: '八'},
    {id: 9, value: '九'},
    {id: 10, value: '十'},
]

function getStringByNum(num) {
    for (var i in numToStringArr) {
        if (num == numToStringArr[i].id) {
            return numToStringArr[i].value;
        }
    }
}

function downFile(url) {
    var name = url.substring(url.lastIndexOf("/") + 1);
    console.log(name);
    var $a = $("<a target='_blank'></a>").attr("href", url).attr("download", name);
    $a[0].click();
}

//过去时间
function getTimeString(timestamp) {
    var nowTimestamp = new Date().getTime();
    var count = (nowTimestamp - timestamp) / 1000;
    if (count <= 0) {
        return '刚刚';
    } else if (count <= 60) {
        return Math.floor(count) + '秒前';
    } else if (count <= 60 * 60) {
        return Math.floor(count / 60) + '分钟前'
    } else if (count <= 60 * 60 * 24) {
        return Math.floor(count / 60 / 60) + '小时前'
    } else if (count <= 60 * 60 * 24 * 30) {
        return Math.floor(count / 60 / 60 / 24) + '天前'
    } else if (count <= 60 * 60 * 24 * 365) {
        return Math.floor(count / 60 / 60 / 24 / 30) + '月前'
    } else {
        return Math.floor(count / 60 / 60 / 24 / 365) + '年前'
    }
}


// console.log(isToday('2018-8-14')); //返回true
function prefixInteger(num, length) {
    return (Array(length).join('0') + num).slice(-length);
}

//流动加载
var scrollFlag = true;

function scrollBottomGetData(callBack) {
    window.addEventListener('scroll', function () {
        //已经滚动到上面的页面高度
        var scrollTop = Math.max(document.body.scrollTop, document.documentElement.scrollTop);
        //页面总高度
        var scrollHeight = Math.max(document.body.scrollHeight, document.documentElement.scrollHeight);
        //浏览器窗口高度
        var windowHeight = (document.compatMode === "CSS1Compat") ? document.documentElement.clientHeight : document.body.clientHeight;
        // console.log(Math.abs(scrollTop + windowHeight - scrollHeight));
        if (Math.abs(scrollTop + windowHeight - scrollHeight) <= 60) {
            if (callBack && scrollFlag) {
                callBack();
                scrollFlag = false;
                setTimeout(function () {
                    scrollFlag = true;
                }, 1000);
            }
        }
    });
}

//判断是否是图片类型
function checkImg(files) {
    if (!files || files.length === 0) {
        return false;
    }
    for (var i = 0; i < files.length; i++) {
        if (!/image\/\w+/.test(files[0].type)) {
            return false;
        }
    }
    return true;
}

//判断文件是
// 'docx',, 'xlsx'
var limitWorkArr = ['doc', 'pdf', 'xls', 'txt'];

function checkWorkFile(files) {
    if (!files || files.length === 0) {
        return false;
    }
    for (var i = 0; i < files.length; i++) {
        if (typeof files[i] === 'object') {
            var filename = files[i].name;
            var pointIndex = filename.indexOf('.');
            var suffix = filename.substr(pointIndex + 1);
            var findIndex = limitWorkArr.findIndex(function (item) {
                return item === suffix;
            });
            if (findIndex === -1)
                return false;
        }
    }
    return true;
}

//获取formData
var getFileForm = function (files, form) {
    var formData = form || new FormData();
    for (var i in files) {
        if (typeof files[i] === 'object')
            formData.append('file' + i, files[i]);
    }
    return formData;
}

//复制一个对象
function cloneObj(obj) {
    var temp = null;
    if (obj instanceof Array) {
        temp = obj.concat();
    } else if (obj instanceof Function) {
        //函数是共享的是无所谓的，js也没有什么办法可以在定义后再修改函数内容
        temp = obj;
    } else {
        temp = new Object();
        for (var item in obj) {
            var val = obj[item];
            temp[item] = typeof val == 'object' ? clone(val) : val; //这里也没有判断是否为函数，因为对于函数，我们将它和一般值一样处理
        }
    }
    return temp;
}

//下载文件
function downloadFile(url) {
    try {
        var elemIF = document.createElement("iframe");
        elemIF.src = url;
        elemIF.style.display = "none";
        document.body.appendChild(elemIF);
    } catch (e) {

    }
}

//兼容写法
if (!Object.keys) {
    Object.keys = (function () {
        var hasOwnProperty = Object.prototype.hasOwnProperty,
            hasDontEnumBug = !({toString: null}).propertyIsEnumerable('toString'),
            dontEnums = [
                'toString',
                'toLocaleString',
                'valueOf',
                'hasOwnProperty',
                'isPrototypeOf',
                'propertyIsEnumerable',
                'constructor'
            ],
            dontEnumsLength = dontEnums.length;

        return function (obj) {
            if (typeof obj !== 'object' && typeof obj !== 'function' || obj === null) throw new TypeError('Object.keys called on non-object');

            var result = [];

            for (var prop in obj) {
                if (hasOwnProperty.call(obj, prop)) result.push(prop);
            }

            if (hasDontEnumBug) {
                for (var i = 0; i < dontEnumsLength; i++) {
                    if (hasOwnProperty.call(obj, dontEnums[i])) result.push(dontEnums[i]);
                }
            }
            return result;
        }
    })()
};

function hpclearCache(){
	var username = localStorage.getItem("username");
//	var token = localStorage.getItem("token");
//	var type = localStorage.getItem("type");
	localStorage.clear();
	localStorage.setItem("username",username);
//	localStorage.setItem("token",token);
//	localStorage.setItem("type",type);
}


// 滚动加载触发
function weuiLoadmore(callBack) {
    var loading = false;  //状态标记
    $(document.body).infinite().on("infinite", function () {
        if (loading) return;
        loading = true;
        setTimeout(function () {
            if (callBack) callBack();
            loading = false;
        }, 1500);   //模拟延迟
        $(document.body).destroyInfinite()
    });
}

// 下拉刷新触发
function weuiPullrefresh(callBack) {
    $(document.body).pullToRefresh(function () {
        if (callBack) callBack();
        $(document.body).pullToRefreshDone();
    });
}